<!-- src/components/topology-editor/MissileDeviceNode.vue -->
<template>
  <div class="missile-device-node" :style="nodeStyle">
    <!-- 顶部连接点 - 新增 -->
    <Handle
      v-if="!isPowerDistribution"
      :id="getTopHandleId()"
      type="source"
      :position="Position.Top"
      class="top-handle main-connector"
      :style="getMainConnectorStyle()"
    />

    <!-- SYS-008 特殊处理：顶部和底部连接点 -->
    <Handle
      v-if="isPowerDistribution"
      :id="'MAIN_IN'"
      type="target"
      :position="Position.Top"
      class="top-handle power-in"
      :style="getPowerConnectorStyle('input')"
    />
    <Handle
      v-if="isPowerDistribution"
      :id="'MAIN_RTN'"
      type="source"
      :position="Position.Bottom"
      class="bottom-handle power-return"
      :style="getPowerConnectorStyle('return')"
    />

    <!-- 节点头部 - 设备基本信息 -->
    <div class="node-header" :style="headerStyle">
      <div class="device-icon">
        <n-icon :component="getDeviceIcon(data.type)" :size="16" />
      </div>
      <div class="device-info">
        <div class="device-name">{{ data.label }}</div>
        <div class="device-id">{{ data.type }}</div>
      </div>
    </div>

    <!-- 针脚列表 -->
    <div class="pins-container">
      <div
        v-for="connector in data.connectors"
        :key="connector.id"
        class="connector-section"
      >
        <div class="connector-title">
          {{ connector.id }} ({{ connector.type }})
        </div>
        <div v-for="pin in getFilteredPins(connector.pins)" :key="pin.id" class="pin-row">
          <!-- 左侧连接点 -->
          <Handle
            v-if="shouldShowHandle(pin.direction, 'left')"
            :id="getPinHandleId(connector.id, pin.id)"
            type="source"
            :position="Position.Left"
            class="pin-handle left-handle"
            :style="getPinHandleStyle(pin.type)"
          />

          <!-- 针脚信息 -->
          <div class="pin-info" :title="getPinTooltip(pin)">
            <span class="pin-id">{{ pin.id }}</span>
            <span class="pin-name">{{ pin.name }}</span>
            <span class="pin-direction" :class="pin.direction">
              {{ getDirectionSymbol(pin.direction) }}
            </span>
          </div>

          <!-- 右侧连接点 -->
          <Handle
            v-if="shouldShowHandle(pin.direction, 'right')"
            :id="getPinHandleId(connector.id, pin.id)"
            type="target"
            :position="Position.Right"
            class="pin-handle right-handle"
            :style="getPinHandleStyle(pin.type)"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from "vue";
import { Handle, Position } from "@vue-flow/core";
import { NIcon } from "naive-ui";
import {
  HardwareChipOutline,
  AnalyticsOutline,
  NavigateOutline,
  GitMergeOutline,
  RadioOutline,
  ShieldCheckmarkOutline,
  WifiOutline,
  ServerOutline,
  FlashOutline,
  GitBranchOutline,
} from "@vicons/ionicons5";

const props = defineProps({
  data: {
    type: Object,
    required: true,
  },
  selected: {
    type: Boolean,
    default: false,
  },
});

// 判断是否是电源分配单元
const isPowerDistribution = computed(() => {
  return props.data.type === "SYS-008";
});

// 过滤针脚 - 对于 SYS-008，过滤掉 MAIN_IN 和 MAIN_RTN
const getFilteredPins = (pins) => {
  if (!isPowerDistribution.value) {
    return pins || []
  }
  
  // 过滤掉 MAIN_IN 和 MAIN_RTN，它们已经作为顶部和底部连接点单独显示
  return (pins || []).filter(pin => 
    pin.id !== 'MAIN_IN' && pin.id !== 'MAIN_RTN'
  )
}

// 节点样式 - 移除内边距，使用绝对定位
const nodeStyle = {
  border: `2px solid ${props.data.specifications?.color || "#2080f0"}`,
  borderRadius: "8px",
  background: "white",
  width: "100%",
  height: "100%",
  display: "flex",
  flexDirection: "column",
  fontSize: "11px",
  boxShadow: props.selected ? "0 0 0 2px #2080f0" : "0 2px 8px rgba(0,0,0,0.1)",
  overflow: "hidden",
  position: "relative", // 重要：为连接点定位提供参考
};

// 头部样式
const headerStyle = {
  background: props.data.specifications?.color || "#2080f0",
  color: "white",
  padding: "6px 8px",
  display: "flex",
  alignItems: "center",
  gap: "6px",
  borderBottom: "1px solid #e1e5e9",
  flexShrink: 0,
  height: "40px", // 固定头部高度
};

// 获取顶部连接点ID
const getTopHandleId = () => {
  return `${props.data.type}-J1`;
};

// 获取主连接器样式
const getMainConnectorStyle = () => {
  return {
    borderRadius: "50%",
    width: "12px",
    height: "12px",
    background: "#339af0",
    border: "2px solid #1864ab",
    top: "-6px",
  };
};

// 获取电源连接器样式
const getPowerConnectorStyle = (type) => {
  const baseStyle = {
    borderRadius: '50%',
    width: '14px',
    height: '14px',
    left: '50%',
    transform: 'translateX(-50%)'
  }
  
  if (type === 'input') {
    return {
      ...baseStyle,
      background: '#ff6b6b',
      border: '2px solid #c92a2a',
      top: '-7px'
    }
  } else {
    return {
      ...baseStyle,
      background: '#495057',
      border: '2px solid #212529',
      bottom: '-7px'
    }
  }
}

// 获取设备图标
const getDeviceIcon = (deviceType) => {
  const iconMap = {
    "SYS-001": HardwareChipOutline,
    "SYS-002": AnalyticsOutline,
    "SYS-003": NavigateOutline,
    "SYS-004": GitMergeOutline,
    "SYS-005": RadioOutline,
    "SYS-006": ShieldCheckmarkOutline,
    "SYS-007": WifiOutline,
    "SYS-008": ServerOutline,
    "SYS-009": FlashOutline,
    "SYS-010": GitBranchOutline,
  };
  return iconMap[deviceType] || HardwareChipOutline;
};

// 获取针脚连接点ID
const getPinHandleId = (connectorId, pinId) => {
  return `${connectorId}-${pinId}`;
};

// 判断是否显示连接点
const shouldShowHandle = (direction, position) => {
  if (position === "left") {
    // 输出、双向、return 都显示左侧连接点
    return (
      direction === "output" ||
      direction === "bidirectional" ||
      direction === "return"
    );
  } else if (position === "right") {
    // 输入、双向、return 都显示右侧连接点
    return (
      direction === "input" ||
      direction === "bidirectional" ||
      direction === "return"
    );
  }
  return false;
};

// 获取针脚连接点样式
const getPinHandleStyle = (pinType, direction) => {
  const colorMap = {
    power: "#ff6b6b",
    ground: "#495057",
    data: "#339af0",
    analog: "#51cf66",
    bus: "#cc5de8",
    discrete: "#ff922b",
    ethernet: "#20c997",
    fiber: "#e599f7",
  };

  const borderColorMap = {
    power: "#c92a2a",
    ground: "#212529",
    data: "#1864ab",
    analog: "#2b8a3e",
    bus: "#9c36b5",
    discrete: "#e67700",
    ethernet: "#0ca678",
    fiber: "#ae3ec9",
  };

  const baseStyle = {
    borderRadius: "50%",
    width: "8px",
    height: "8px",
  };

  // 为 return 方向使用特殊样式
  if (direction === "return") {
    return {
      ...baseStyle,
      background: "#6c757d", // 使用灰色
      border: `1px solid #495057`,
    };
  }

  return {
    ...baseStyle,
    background: colorMap[pinType] || "#868e96",
    border: `1px solid ${borderColorMap[pinType] || "#495057"}`,
  };
};

// 获取方向符号
const getDirectionSymbol = (direction) => {
  const symbols = {
    input: "←",
    output: "→",
    bidirectional: "↔",
    return: "⤾",
  };
  return symbols[direction] || "•";
};

// 获取针脚提示信息
const getPinTooltip = (pin) => {
  return `${pin.name}\n类型: ${pin.type}\n方向: ${pin.direction}\n信号: ${
    pin.signal || "N/A"
  }`;
};
</script>

<style scoped>
.missile-device-node {
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  user-select: none;
}

.node-header {
  flex-shrink: 0;
}

.device-icon {
  display: flex;
  align-items: center;
}

.device-info {
  flex: 1;
  min-width: 0;
}

.device-name {
  font-weight: 600;
  font-size: 12px;
  line-height: 1.2;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.device-id {
  font-size: 10px;
  opacity: 0.9;
  line-height: 1.2;
}

.pins-container {
  flex: 1;
  overflow: hidden; /* 移除滚动条 */
  display: flex;
  flex-direction: column;
}

.connector-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.connector-title {
  font-size: 9px;
  font-weight: 600;
  color: #666;
  padding: 3px 8px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  flex-shrink: 0;
}

.pin-row {
  display: flex;
  align-items: center;
  height: 22px; /* 固定行高 */
  padding: 0 4px; /* 减少内边距 */
  position: relative;
  border-bottom: 1px solid #f1f3f4;
  flex-shrink: 0;
}

.pin-row:hover {
  background: #f8f9fa;
}

.pin-handle {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1000; /* 提高层级确保不被遮挡 */
}

.left-handle {
  left: -4px; /* 调整到边框外侧 */
}

.right-handle {
  right: -4px; /* 调整到边框外侧 */
}

.pin-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 0 2px;
  min-width: 0;
}

.pin-id {
  font-family: "Courier New", monospace;
  font-size: 9px;
  font-weight: 600;
  color: #495057;
  min-width: 18px;
}

.pin-name {
  flex: 1;
  font-size: 10px;
  color: #212529;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: 0;
}

.pin-direction {
  font-size: 10px;
  font-weight: 600;
  min-width: 12px;
  text-align: center;
}

.pin-direction.input {
  color: #51cf66;
}

.pin-direction.output {
  color: #ff6b6b;
}

.pin-direction.bidirectional {
  color: #339af0;
}

.pin-direction.return {
  color: #495057;
}

/* 自定义连接点样式 - 确保连接点可见 */
:deep(.vue-flow__handle) {
  width: 8px !important;
  height: 8px !important;
  min-width: auto !important;
  min-height: auto !important;
  border-radius: 50% !important;
  z-index: 1000;
}

:deep(.vue-flow__handle-left) {
  left: -4px !important;
}

:deep(.vue-flow__handle-right) {
  right: -4px !important;
}

:deep(.vue-flow__handle-top) {
  top: -6px !important;
  left: 50% !important;
  transform: translateX(-50%) !important;
}

:deep(.vue-flow__handle-bottom) {
  bottom: -6px !important;
  left: 50% !important;
  transform: translateX(-50%) !important;
}

/* 主连接点特殊样式 - 增大尺寸减少间隙 */
:deep(.main-connector) {
  width: 14px !important;
  height: 14px !important;
  top: -7px !important;
  left: 50% !important;
  transform: translateX(-50%) !important;
}

:deep(.power-in) {
  width: 14px !important;
  height: 14px !important;
  top: -7px !important;
  left: 50% !important;
  transform: translateX(-50%) !important;
}

:deep(.power-return) {
  width: 14px !important;
  height: 14px !important;
  bottom: -7px !important;
  left: 50% !important;
  transform: translateX(-50%) !important;
}

/* 确保连接点不被节点内容遮挡 */
:deep(.vue-flow__node) {
  z-index: 1;
}

:deep(.vue-flow__handle) {
  z-index: 2;
}
</style>